#include "tile_sheet.h"

#include <QDebug>
#include <QPixmap>

#include "pack_metadata.h"
#include "tile.h"

TileSheet::TileSheet(QString name,
                     const QPixmap& pixmap,
                     int rows,
                     int columns,
                     const PackMetadata* metadata,
                     QObject *parent)
    : QObject(parent),
      name_(name),
      pixmap_(pixmap),
      rows_(rows),
      columns_(columns),
      pack_metadata_(metadata) {}

QList<Tile*> TileSheet::allTiles() {
  QList<Tile*> ret;
  for (int col = 0; col < columns(); ++col) {
    for (int row = 0; row < rows(); ++row) {
      ret << tile(row, col);
    }
  }
  return ret;
}

QString TileSheet::name() const {
  return name_;
}

const QPixmap& TileSheet::pixmap() const {
  return pixmap_;
}

int TileSheet::rows() const {
  return rows_;
}

int TileSheet::columns() const {
  return columns_;
}

QSize TileSheet::tileSize() const {
  return QSize(pixmap_.width() / columns_, pixmap_.height() / rows_);
}

Tile* TileSheet::tile(int row, int col) {
  QPair<int, int> coords(row, col);
  if (!tile_cache_.contains(coords)) {
    tile_cache_.insert(coords, new Tile(pack_metadata_->tileName(name(), row, col), row, col, this));
  }
  return tile_cache_.value(coords);
}

QDebug& operator<<(QDebug debug, const TileSheet& sheet) {
  debug.nospace() << "TileSheet(" << sheet.name() << ")";
  return debug.space();
}
